57. 插入区间
为保证权益,题目请参考 57. 插入区间(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
vector<vector<int>> insert(vector<vector<int>> &intervals, vector<int> &newInterval)
{
vector<vector<int>> ans;
int i = 0;
// left
while (i < intervals.size() && intervals[i][1] < newInterval[0])
{
ans.push_back(intervals[i]);
i += 1;
}
// middle
while (i < intervals.size() && intervals[i][0] <= newInterval[1])
{
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
i += 1;
}
ans.push_back(newInterval);
// right
while (i < intervals.size())
{
ans.push_back(intervals[i]);
i += 1;
}
return ans;
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46